package com.linchuan.concurrency;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

class Task {}

class TaskGenerator {
  public Task getNextTask(BlockingQueue<Task> queue) {
    boolean interrupted = false;
    try {
      return queue.take();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      return null;
    }
  }
}

class TaskRunner implements Runnable {

  private final TaskGenerator taskGenerator;
  private final BlockingQueue<Task> queue;

  TaskRunner(TaskGenerator taskGenerator, BlockingQueue<Task> queue) {
    this.taskGenerator = taskGenerator;
    this.queue = queue;
  }

  @Override
  public void run() {

    var task = taskGenerator.getNextTask(queue);
    System.out.println(task);
  }
}

public class InterruptionDeadLoop {
  public static void main(String[] args) throws InterruptedException {
    BlockingQueue<Task> queue = new LinkedBlockingQueue<Task>();
    TaskGenerator generator = new TaskGenerator();
    TaskRunner runner = new TaskRunner(generator, queue);
    ExecutorService exec = Executors.newSingleThreadExecutor();
    exec.execute(runner);
    Thread.sleep(100);
    exec.shutdownNow();
    Thread.sleep(100);
    //    queue.offer(new com.linchuan.concurrency.Task());

    Thread thread = new Thread(runner);
    thread.start();
    Thread.sleep(100);
    thread.interrupt();
    Thread.sleep(100);
    queue.offer(new Task());
    System.out.println("wake up!");
    /*thread.interrupt();
    Thread.sleep(100);

    queue.offer(new com.linchuan.concurrency.Task());
    System.out.println("wake up2!");*/
  }
}
